package com.shuqi.activity;

import java.lang.ref.WeakReference;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

import com.shuqi.activity.viewport.CommonTitle;
import com.shuqi.activity.viewport.ToastDialog;
import com.shuqi.application.ShuqiApplication;
import com.shuqi.common.Constant;
import com.shuqi.common.utils.Log4an;
import com.shuqi.controller.AccountBindController;
import com.shuqi.controller.R;
import com.shuqi.controller.ThirdAccountUnbindController;
import com.shuqi.database.model.UserInfo;
import com.shuqi.interfaces.EventTypeConstants;
import com.shuqi.interfaces.IEventListener;
import com.shuqi.model.AccountBindModel;
import com.shuqi.model.manager.MyAccountManager;
import com.shuqi.model.parse.parser.AccountBindParser.AccountBindParserInfo;
import com.shuqi.model.parse.parser.ThirdAccountUnbindParser.ThirdAccountUnbindParserInfo;
import com.shuqi.statistics.StatisticsEventID;
import com.shuqi.statistics.StatisticsUtils;
import com.shuqi.third.FunctionListener;
import com.shuqi.third.SinaFunction;

public class AccountBindActivity extends ActivityBase implements OnClickListener, IEventListener {
    private final String logTag = "AccountBindActivity";

    private AccountBindController mAccountBindController;

    private ThirdAccountUnbindController mAccountUnbindController;

    private ToastDialog mLoadingDialog;

    private SinaBind mSinaBindListener = new SinaBind(this);
    
    private CommonTitle mTitle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_account_bind);
    }

    /**
     * 读取用户信息展示
     */
    private void refreshAccountInfo() {
        UserInfo userInfo = MyAccountManager.getInstance(getApplicationContext(), true);
        if (userInfo != null) {
            bindClickLinstener();
            showBindInfo(userInfo);
            Log4an.i(logTag, userInfo.toString());
        } else {
            Log4an.i(logTag, "userInfo = null");
        }
    }

    private void bindClickLinstener() {
        mTitle = (CommonTitle) findViewById(R.id.title);
        mTitle.setLeftClickListener(this);
        findViewById(R.id.account_binner_bind_mobile_bt).setOnClickListener(this);
        findViewById(R.id.account_binner_bind_email_bt).setOnClickListener(this);
        findViewById(R.id.account_binner_bind_sina_bt).setOnClickListener(this);
    }

    /***
     * 显示用户绑定信息
     * 
     * @param userInfo
     */
    private void showBindInfo(UserInfo userInfo) {
        Log4an.i(logTag, "显示用户绑定信息");
        int level = MyAccountManager.checkUserSafeLevel(userInfo);
        View view = findViewById(R.id.account_bind_level_show);
        TextView tips = (TextView) findViewById(R.id.account_bind_level_tips);
        if (level == UserInfo.USERSAFELEVEL_HIGH) {// 安全级别：高
            view.setBackgroundResource(R.drawable.icon_account_bind_level_high);
            tips.setText("您账户的安全级别为：高");
        } else if (level == UserInfo.USERSAFELEVEL_COMMON) {// 安全级别：中
            view.setBackgroundResource(R.drawable.icon_account_bind_level_common);
            tips.setText("您账户的安全级别为：中");
        } else {// 安全级别：低
            view.setBackgroundResource(R.drawable.icon_account_bind_level_low);
            tips.setText("您账户的安全级别为：低");
        }
        findViewById(R.id.account_top_bindtips);
        // 手机号
        TextView tv_mobile = (TextView) findViewById(R.id.account_binner_bind_mobile_bt);
        TextView tv_mobileshow = (TextView) findViewById(R.id.account_binner_bind_mobileshow);
        if (TextUtils.isEmpty(userInfo.getMobile())) {
            tv_mobileshow.setVisibility(View.GONE);
            changButtonUiState(1, tv_mobile);
        } else {
            tv_mobileshow.setVisibility(View.VISIBLE);
            tv_mobileshow.setText(userInfo.getMobileShow());
            changButtonUiState(2, tv_mobile);
        }
        // 邮箱
        TextView tv_email = (TextView) findViewById(R.id.account_binner_bind_email_bt);
        View email_layout = findViewById(R.id.account_binner_bind_email);
        TextView tv_emailshow = (TextView) findViewById(R.id.account_binner_bind_emailshow);
        if (TextUtils.isEmpty(userInfo.getEmail())) {
            tv_emailshow.setVisibility(View.GONE);
            email_layout.setVisibility(View.GONE);
            findViewById(R.id.account_binner_bind_email_line).setVisibility(View.GONE);
            changButtonUiState(1, tv_email);
        } else {
            tv_emailshow.setVisibility(View.VISIBLE);
            tv_emailshow.setText(userInfo.getEmailShow());
            changButtonUiState(2, tv_email);
        }

        TextView tv_sina = (TextView) findViewById(R.id.account_binner_bind_sina_bt);
        TextView tv_sinashow = (TextView) findViewById(R.id.account_binner_bind_sinashow);
        if (TextUtils.isEmpty(userInfo.getSinaKey())) {
            tv_sinashow.setVisibility(View.GONE);
            changButtonUiState(1, tv_sina);
        } else {
            tv_sinashow.setVisibility(View.VISIBLE);
            tv_sinashow.setText(userInfo.getSinaName());
            changButtonUiState(3, tv_sina);
        }
    }

    /***
     * 更改按钮的UI状态
     * 
     * @param state 1可绑定，2已绑定，3解绑
     * @param textView
     */
    private void changButtonUiState(int state, TextView textView) {
        switch (state) {
            case 1:
                textView.setText("绑定");
                textView.setBackgroundResource(R.drawable.btn_common_green_ok);
                textView.setTextColor(Color.WHITE);
                textView.setClickable(true);
                break;
            case 2:
                textView.setText("已绑定");
                textView.setBackgroundColor(Color.TRANSPARENT);
                textView.setTextColor(0xff14be7d);
                textView.setClickable(false);
                break;
            case 3:
                textView.setText("解绑");
                textView.setBackgroundResource(R.drawable.btn_common_red);
                textView.setTextColor(Color.WHITE);
                textView.setClickable(true);
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_left:
                ActivityManager.getInstance().finishActivity(this);
                break;
            case R.id.account_binner_bind_mobile_bt:
                StatisticsUtils.onEvent(StatisticsEventID.ACCOUNT_BIND_MOBILE_CLICK);
                AccountMobileBindActivity.show(this, AccountMobileBindActivity.TYPE_BIND);
                break;
            case R.id.account_binner_bind_email_bt:
                StatisticsUtils.onEvent(StatisticsEventID.ACCOUNT_BIND_EMIAL_CLICK);
                AccountMailBindActivity.show(this);
                break;
            case R.id.account_binner_bind_sina_bt:
                clickBindBtn();
                break;

        }

    }

    private void clickBindBtn() {
        UserInfo user = MyAccountManager.getInstance(getApplicationContext());
        boolean isSinaAlreadyBind = user != null && !TextUtils.isEmpty(user.getSinaKey());
        if (isSinaAlreadyBind) {
            StatisticsUtils.onEvent(StatisticsEventID.ACCOUNT_BIND_SINA_UNBIND);
            unBindSina();
        } else {
            StatisticsUtils.onEvent(StatisticsEventID.ACCOUNT_BIND_SINA_BIND);
            bindSina();
        }

    }

    private void bindSina() {
        if (!checkUserId()) {
            return;
        }

        SinaFunction.login(this, true, mSinaBindListener);
    }

    private boolean checkUserId() {
        UserInfo user = MyAccountManager.getInstance(getApplicationContext());
        if (user == null || TextUtils.isEmpty(user.getUserId())
                || Constant.GUEST_USER_ID.equals(user.getUserId())) {
            return false;
        }
        return true;
    }

    private void unBindSina() {
        if (!checkUserId()) {
            return;
        }
        if (mAccountUnbindController == null) {
            mAccountUnbindController = new ThirdAccountUnbindController(this);
            mAccountUnbindController.addEventListener(this);
        }
        showLoadingDialog(true, false, "正在解绑新浪微博");
        UserInfo user = MyAccountManager.getInstance(getApplicationContext());
        mAccountUnbindController.unBind(user.getUserId(), ThirdAccountUnbindController.TYPE_SINA,
                user.getSinaKey());

    }

    private void bindSinaCallBack(String key, String weiboName) {
        if (mAccountBindController == null) {
            mAccountBindController = new AccountBindController(this);
            mAccountBindController.addEventListener(this);
        }
        mAccountBindController.bind(key, null, AccountBindModel.TYPE_BIND_SINA, null, weiboName);
    }

    @Override
    protected void onResume() {
        refreshAccountInfo();
        super.onResume();
    }

    @Override
    public void activityLogicForward() {

    }

    @Override
    public void activityInitData() {

    }

    @Override
    public void onEvent(int event, Object data) {
        if (isFinishing()) {
            return;
        }
        switch (event) {
            case EventTypeConstants.EVENT_SUCCESS:
                if (data != null && data instanceof AccountBindParserInfo) {
                    onSinaBindNetCallback(data);
                } else if (data != null && data instanceof ThirdAccountUnbindParserInfo) {
                    onSinaUnbindNetCallback(data);
                }

                break;
            default:
                hideLoadingDialog();
                showMsg("网络连接超时");
                break;
        }
    }

    /**
     * 
     * @param info 存入解绑新浪的用户信息
     */
    private void updateUnBindSinaToDB() {
        UserInfo user = MyAccountManager.getInstance(getApplicationContext());
        if (user == null) {
            return;
        }
        user.setSinaKey("");
        user.setNickName("");
        MyAccountManager.onUnBindSinaSuccesee(user.getUserId());
    }

    /**
     * 
     * @param info 存入最新的用户信息
     */
    private void updateBindUserInfoToDB(AccountBindParserInfo info) {
        UserInfo user = MyAccountManager.getInstance(getApplicationContext());
        if (user == null) {
            return;
        }
        if (!TextUtils.isEmpty(info.thirdKey)) {
            user.setSinaKey(info.thirdKey);
        }
        if (!TextUtils.isEmpty(info.thirdNickName)) {
            user.setSinaName(info.thirdNickName);
        }
        if (!TextUtils.isEmpty(info.session)) {
            user.setSession(info.session);
        }
        MyAccountManager.onUpdateUserInfo(user);
    }

    private void onSinaUnbindNetCallback(final Object data) {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                ThirdAccountUnbindParserInfo info = (ThirdAccountUnbindParserInfo) data;
                hideLoadingDialog();
                if (info != null) {
                    String msg = info.message;
                    if ("1".equals(info.code)) {
                        // 成功解绑
                        updateUnBindSinaToDB();
                        AccountActivity.callRefreshAccountOnResume();
                        // 更新页面
                        refreshAccountInfo();
                    }
                    if (!TextUtils.isEmpty(msg)) {
                        showMsg(msg);
                    }
                }
            }
        };
        ShuqiApplication.getApplicationHandler().post(r);
    }


    private void onSinaBindNetCallback(final Object data) {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                AccountBindParserInfo info = (AccountBindParserInfo) data;
                hideLoadingDialog();
                if (info != null) {
                    String msg = info.message;
                    if (info.resultCode == 200) {
                        updateBindUserInfoToDB(info);
                        AccountActivity.callRefreshAccountOnResume();
                        refreshAccountInfo();
                    }
                    if (!TextUtils.isEmpty(msg)) {
                        showMsg(msg);
                    }
                }
            }
        };
        ShuqiApplication.getApplicationHandler().post(r);
    }


    private void showLoadingDialog(boolean isLoading, boolean isSuccess, String showText) {
        if (isFinishing()) {
            return;
        }
        if (mLoadingDialog == null) {
            mLoadingDialog = new ToastDialog(this);
            mLoadingDialog.setDissmisOnClickOutSide(false);
        }
        if (isLoading) {
            mLoadingDialog.loading(showText);
            return;
        }
        mLoadingDialog.show(isSuccess, showText);

    }

    private void hideLoadingDialog() {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                if (mLoadingDialog != null) {
                    mLoadingDialog.dismiss();
                }
            }
        };
        ShuqiApplication.getApplicationHandler().post(r);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mLoadingDialog != null) {
            mLoadingDialog.dismiss();
        }
    }

    /**
     * 打开账户绑定页
     * 
     * @param context
     */
    public static void show(Activity context) {
        Intent intent = new Intent(context, AccountBindActivity.class);
        ActivityManager.getInstance().startNextActivity(intent, context);
    }


    // sina funcation
    public static class SinaBind implements FunctionListener {

        WeakReference<AccountBindActivity> ref;

        public SinaBind(AccountBindActivity activity) {
            ref = new WeakReference<AccountBindActivity>(activity);
        }

        private boolean isActivityActive() {
            return ref != null && ref.get() != null && !ref.get().isFinishing();
        }

        @Override
        public void onComplete(final String uid) {
            if (!isActivityActive()) {
                return;
            }
            // sina 返回结果 在onShow中登录我们的接口
            ShuqiApplication.getApplicationHandler().post(new Runnable() {

                @Override
                public void run() {
                    if (!isActivityActive()) {
                        return;
                    }
                    ref.get().showLoadingDialog(true, false, "正在绑定新浪微博");
                }
            });

        }

        @Override
        public void onError() {
            if (!isActivityActive()) {
                return;
            }
            ref.get().hideLoadingDialog();
            ref.get().showMsg("新浪微博连接失败");
        }

        @Override
        public void onShow(String name, String uid) {
            ref.get().bindSinaCallBack(uid, name);
        }

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent != null) {
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            finish();
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            ActivityManager.getInstance().finishActivity(this);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
